function [ varargout ] = divasl_get_filelist( varargin )
%Divasl_get_filelist Summary of this function goes here
%   Detailed explanation goes here

if nargin < 2
    prefix_ti = '';
elseif nargin == 2
    prefix_ti = varargin{2};
end

if ~isa(varargin{1},'struct')
    error('Error Here');
else
    parameters = varargin{1};
end

if ~isfield(parameters,'path')
    error('path parameters havenot been set');
end

if ~isfield(parameters.path,{'dir','project','sequence','prefix'})
    error('path is not fully set, check it');
end

f_dir = fullfile(...
    parameters.path.dir,...
    parameters.path.project,...
    parameters.path.sequence);
f_filter = [parameters.path.prefix,prefix_ti];
seq_file = get_file(f_dir,f_filter);

seq_num = length(seq_file);


%% File list for coregistered M0
f_list = cell(seq_num,1);
for i = 1:seq_num
    if isdir(seq_file{i})
        f_list{i} = fullfile(seq_file{i},parameters.path.names.com0);
        if ~exist(f_list{i},'file')
            error(['File ',f_list{i},' does not exist']);
        end
    end
end

varargout{1} = f_list;

%% File list for coregistered ASL
f_list = cell(seq_num,1);
for i = 1:seq_num
    if isdir(seq_file{i})
        f_list{i} = fullfile(seq_file{i},parameters.path.names.coasl);
        if ~exist(f_list{i},'file')
            error(['File ',f_list{i},' does not exist']);
        end
    end
end

varargout{2} = f_list;

%% File list for coregistered MRI
f_list = cell(seq_num,1);
for i = 1:seq_num
    if isdir(seq_file{i})
        f_list{i} = fullfile(seq_file{i},parameters.path.names.align);
        if ~exist(f_list{i},'file')
            error(['File ',f_list{i},' does not exist']);
        end
    end
end

varargout{3} = f_list;

end


function f_list = get_file(f_dir,f_filter)
% Search files containing f_filter in the directory f_dir, then return the
% fullfile list in f_list.
searchname = ['*',f_filter,'*'];
listname = dir(fullfile(f_dir,searchname));
if ~isempty(listname)
    f_list = cell(length(listname),1);
    for i = 1:length(listname)
        f_list{i} = fullfile(f_dir,listname(i).name);
    end
end
end

